﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;

namespace HIWSystem.ViewModel
{
    public class PackingPrintViewModel : ViewModelBase
    {
        //用于判断是不是第一次触发过滤，是则备份原始数据源
        private bool isFirstFilterPN = true;
        //当没有输入内容时恢复到备份的原始数据源
        ObservableCollection<PartNumberEntity> backupPNs = null;

        #region 属性
        bool isFirstScan = true; //首次扫描标识
        int firstScanPackingNum = 0;//每箱包装数量
        string firstScanPN = string.Empty;//首次扫描的机种
        int scanNum = 0;//扫描的数量
        string inputSn = string.Empty; //录入的SN

        private string sn="";
        /// <summary>
        /// 包装序列号
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private string pn="MODEL";
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private int packingNum;
        /// <summary>
        /// 包装数量
        /// </summary>
        public int PackingNum
        {
            get { return packingNum; }
            set { packingNum = value; this.RaisePropertyChanged(() => PackingNum); }
        }
        private string pnType="滤波器";
        /// <summary>
        /// 机种类型《天线、滤波器、马达等》
        /// </summary>
        public string PnType
        {
            get { return pnType; }
            set { pnType = value; this.RaisePropertyChanged(() => PnType); }
        }
        private Visibility prepackingSnsGridVisibility=Visibility.Collapsed;
        /// <summary>
        /// 预打印网格列表的可见性
        /// </summary>
        public Visibility PrepackingSnsGridVisibility
        {
            get { return prepackingSnsGridVisibility; }
            set { prepackingSnsGridVisibility = value; this.RaisePropertyChanged(() => PrepackingSnsGridVisibility); }
        }
        private ObservableCollection<string> prepackingSns;
        /// <summary>
        /// 一箱包装的序列号集合
        /// </summary>
        public ObservableCollection<string> PrepackingSns
        {
            get { return prepackingSns; }
            set { prepackingSns = value; this.RaisePropertyChanged(() => PrepackingSns); }
        }
        private ObservableCollection<SNEntity> lastStatus;
        /// <summary>
        /// 序列号最后状态信息
        /// </summary>
        public ObservableCollection<SNEntity> LastStatus
        {
            get { return lastStatus; }
            set { lastStatus = value; this.RaisePropertyChanged(() => LastStatus); }
        }
        private ObservableCollection<TrackingEntity> tracking;
        /// <summary>
        /// 序列号的过程信息
        /// </summary>
        public ObservableCollection<TrackingEntity> Tracking
        {
            get { return tracking; }
            set { tracking = value; this.RaisePropertyChanged(() => Tracking); }
        }
        private bool isEnabledPackingPrintButton=false;
        /// <summary>
        /// 是否启用包装打印按钮
        /// </summary>
        public bool IsEnabledPackingPrintButton
        {
            get { return isEnabledPackingPrintButton; }
            set { isEnabledPackingPrintButton= value; this.RaisePropertyChanged(() => IsEnabledPackingPrintButton); }
        }
        private bool isEnabledCheckButton=true;
        /// <summary>
        /// 是否启用检查按钮
        /// </summary>
        public bool IsEnabledCheckButton
        {
            get { return isEnabledCheckButton; }
            set { isEnabledCheckButton=value; this.RaisePropertyChanged(() => IsEnabledCheckButton); }
        }
        private bool snTextBoxFocusable = true;
        /// <summary>
        /// 是否聚焦序列号文本框
        /// </summary>
        public bool SnTextBoxFocusable
        {
            get { return snTextBoxFocusable; }
            set { snTextBoxFocusable = value; this.RaisePropertyChanged(() => SnTextBoxFocusable); }
        }
        private string templateName = "";
        /// <summary>
        /// 包装标签模板名称
        /// </summary>
        public string TemplateName
        {
            get { return templateName; }
            set { templateName = value; this.RaisePropertyChanged(() => TemplateName); }
        }
        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否展开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private int selectIndex;
        /// <summary>
        /// 机种集合中的下标
        /// </summary>
        public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; this.RaisePropertyChanged(() => SelectIndex); }
        }
        #endregion

        #region 命令
        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get
            {
                if (loadedPageCmd == null)
                {
                    loadedPageCmd = new RelayCommand(LoadedPage);
                }
                return loadedPageCmd;
            }
            set { loadedPageCmd = value; }
        }

        private RelayCommand checkCmd;

        public RelayCommand CheckCmd
        {
            get 
            {
                if (checkCmd==null)
                {
                    checkCmd = new RelayCommand(Check);
                }
                return checkCmd;
            }
            set { checkCmd = value; }
        }
        private RelayCommand packingPrintCmd;

        public RelayCommand PackingPrintCmd
        {
            get 
            {
                if (packingPrintCmd==null)
                {
                    packingPrintCmd = new RelayCommand(PackingPrint);
                }
                return packingPrintCmd; 
            }
            set { packingPrintCmd = value; }
        }
        private RelayCommand packingSnKeyEnterCommand;

        public RelayCommand PackingSNKeyEnterCommand
        {
            get 
            {
                if (packingSnKeyEnterCommand == null)
                {
                    packingSnKeyEnterCommand = new RelayCommand(PackingSNEnterHandler);
                }
                return packingSnKeyEnterCommand; 
            }
            set { packingSnKeyEnterCommand = value; }
        }
        

        private RelayCommand filterPNCmd;

        public RelayCommand FilterPNCmd
        {
            get
            {
                if (filterPNCmd == null)
                {
                    filterPNCmd = new RelayCommand(FilterPN);
                }
                return filterPNCmd;
            }
            set { filterPNCmd = value; }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            FillPNsToComboBox();
        }
        /// <summary>
        /// 检测
        /// </summary>
        private void Check()
        {

            string retMsg = string.Empty;//检查的结果
            DataTable dtPN = new DataTable();
            DataTable dtLastStatus = new DataTable();
            DataTable dtTracking = new DataTable();
            List<DataTable> lstTables = new List<DataTable>();//序列号信息
            inputSn = this.SN.ToUpper() ?? "";
            this.SN = "";
            if (inputSn == "")
            {
                MessageBox.Show("输入的序列号不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                this.SnTextBoxFocusable = true;
                return;
            }
            var behindPN = BusinessProcess.SnOwnerPN(inputSn);
            if (behindPN != PN)
            {
                MessageBox.Show(string.Format("输入的条码【{0}】不属于机种【{1}】.\r\n请确认输入的信息是否正确?如果正确请切换机种信息.", inputSn, PN), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            retMsg = BusinessProcess.VerifyPackingWorkStation(inputSn, lstTables); //retMsg-->OK|OK!
            string[] arrayMsg = new string[2];
            arrayMsg = retMsg.Split('|');
            //检查没有问题
            if (arrayMsg[0] == "OK")
            {
                dtPN = lstTables[lstTables.Count - 3];
                dtLastStatus = lstTables[lstTables.Count - 2];
                dtTracking = lstTables[lstTables.Count - 1];
                if (dtPN.Rows.Count > 0)
                {
                    this.PN = dtPN.Rows[0]["PartNumber"].ToString();
                    this.PackingNum = Convert.ToInt32(dtPN.Rows[0]["PerBoxNum"] == DBNull.Value ? "0" : dtPN.Rows[0]["PerBoxNum"].ToString() ?? "0");
                    this.PnType = dtPN.Rows[0]["PnType"].ToString();
                    this.TemplateName = dtPN.Rows[0]["TemplateName"].ToString();
                }
                if (isFirstScan)
                {
                    firstScanPN = this.PN;
                    firstScanPackingNum = this.PackingNum;
                    isFirstScan = false;
                    //首次扫描并且是一箱多包情况记录第一个序列号信息
                    if (this.PackingNum > 1)
                    {
                        this.PrepackingSnsGridVisibility = Visibility.Visible;//启用网格
                        scanNum += 1; //当前扫描的数量
                        if (PrepackingSns == null)
                        {
                            PrepackingSns = new ObservableCollection<string>();
                        }
                        PrepackingSns.Add(inputSn);
                        this.SN = "";
                        this.SnTextBoxFocusable = true;
                    }
                    else if (this.packingNum == 1)
                    {
                        this.IsEnabledCheckButton = false;
                        this.IsEnabledPackingPrintButton = true;
                        PackingPrint();//跳转到打印
                    }
                }
                //非第一次扫描证明是在操作一箱多包的情况
                else
                {
                    if (this.PackingNum == 1)
                    {
                        MessageBoxResult msgResult = MessageBox.Show("当前序列号【" + inputSn + "】对应的是一箱包一个产品,目前的操作是一箱多包的.你是要放弃本次操作吗？", "软件温馨提示！", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                        if (msgResult == MessageBoxResult.OK)
                        {
                            isFirstScan = true;
                            scanNum = 0;
                            firstScanPackingNum = 0;
                            firstScanPN = string.Empty;
                            PrepackingSns = new ObservableCollection<string>();
                            this.PrepackingSnsGridVisibility = Visibility.Collapsed;
                            this.SnTextBoxFocusable = true;
                        }
                        else
                        {
                            this.SnTextBoxFocusable = true;
                        }
                    }
                    else
                    {
                        //判断扫描的机种是否一样
                        if (this.PN != firstScanPN)
                        {
                            MessageBox.Show("本次扫描序列号【" + inputSn + "】对应的机种【" + this.PN + "】和第一次扫描的机种【" + firstScanPN + "】不是同一个机种。\r\n请重新扫描！", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                            this.SnTextBoxFocusable = true;
                        }
                        //扫描的是同一个机种
                        else
                        {
                            //表示已经扫描完毕
                            if (scanNum == firstScanPackingNum)
                            {
                                this.IsEnabledCheckButton = false;
                                this.IsEnabledPackingPrintButton = true;
                            }
                            else
                            {
                                scanNum += 1;
                                PrepackingSns.Add(inputSn);
                                this.SnTextBoxFocusable = true;
                            }
                        }

                    }

                }
            }
            else
            {
                MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 包装打印
        /// </summary>
        private void PackingPrint()
        {
            string[] arrayMsg = new string[2]; //截取返回的状态码和状态信息
            string startTime = string.Empty;
            TrackingEntity trackingEntity = new TrackingEntity();
            DataTable dtLastStatus = new DataTable();//序列号最后的状态
            DataTable dtTracking = new DataTable();//序列号测试Log记录
            List<DataTable> lstDts = new List<DataTable>();
            string retMsg = string.Empty;
            //目前不需要打印，只需要记录数据后面可以再开发
            //一箱多包
            if (firstScanPackingNum > 1)
            {
                //这里后面可以加上打印逻辑
                //***********************
                //
                //
                //***********************
                StringBuilder strSn = new StringBuilder();//多个序列号拼接的字符串信息
                for (int i = 0; i < PrepackingSns.Count; i++)
                {
                    if (i == PrepackingSns.Count - 1) //当循环到最后一次时不加分隔符,防止传到后台切割的时候会出现空序列号
                    {
                        strSn.Append(PrepackingSns[i]);
                    }
                    else
                    {
                        strSn.Append(PrepackingSns[i]+"|");
                    }
                    
                }
                startTime = DateTime.Now.ToString();
                trackingEntity.Sn = strSn.ToString();
                trackingEntity.Station = "PACKING";
                trackingEntity.Result = "PASS";
                trackingEntity.EquipmentName = Environment.MachineName;
                trackingEntity.StartTime = startTime;
                trackingEntity.StopTime = DateTime.Now.ToString();
                trackingEntity.Actor = LogInInfo.User;
                retMsg = BusinessProcess.AddBatchPackingTracking(trackingEntity,out dtLastStatus);
                arrayMsg = retMsg.Split('|');
                if (arrayMsg[0] == "OK")
                {
                    LastStatus = new ObservableCollection<SNEntity>();
                    for (int i = 0; i < dtLastStatus.Rows.Count; i++)
                    {
                        LastStatus.Add(new SNEntity
                        {
                            SN = dtLastStatus.Rows[i]["Sn"].ToString() ?? "",
                            WO = dtLastStatus.Rows[i]["WO"].ToString() ?? "",
                            PN = dtLastStatus.Rows[i]["PN"].ToString() ?? "",
                            CompletedStation = dtLastStatus.Rows[i]["CompletedStation"].ToString() ?? "",
                            PretestStation = dtLastStatus.Rows[i]["PretestStation"].ToString() ?? "",
                            IsEnd = dtLastStatus.Rows[i]["IsEnd"].ToString() == "Y" ? "是" : "否",
                            Actor = dtLastStatus.Rows[i]["Actor"].ToString(),
                            CreateAt = dtLastStatus.Rows[i]["CreateAt"].ToString()
                        });
                    }
                    this.IsEnabledCheckButton = true;
                    this.IsEnabledPackingPrintButton = false;
                    this.SnTextBoxFocusable = true;
                    isFirstScan = true;
                }
                else
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            //一箱单包
            else if (firstScanPackingNum == 1)
            {

                startTime = DateTime.Now.ToString();
                trackingEntity.Sn = inputSn;
                trackingEntity.Station = "PACKING";
                trackingEntity.Result = "PASS";
                trackingEntity.EquipmentName = Environment.MachineName;
                trackingEntity.StartTime = startTime;
                trackingEntity.StopTime = DateTime.Now.ToString();
                trackingEntity.Actor = LogInInfo.User;
                retMsg = BusinessProcess.AddPackingTracking(trackingEntity, lstDts);
                arrayMsg = retMsg.Split('|');
                if (arrayMsg[0] == "OK")
                {
                    this.IsEnabledCheckButton = true;
                    this.IsEnabledPackingPrintButton = false;
                    this.SnTextBoxFocusable = true;
                    isFirstScan = true;
                    if (lstDts.Count >= 2)
                    {
                        dtLastStatus = lstDts[0];
                        LastStatus = new ObservableCollection<SNEntity>();
                        for (int i = 0; i < dtLastStatus.Rows.Count; i++)
                        {
                            LastStatus.Add(new SNEntity
                            {
                                SN = dtLastStatus.Rows[i]["Sn"].ToString() ?? "",
                                WO = dtLastStatus.Rows[i]["WO"].ToString() ?? "",
                                PN = dtLastStatus.Rows[i]["PN"].ToString() ?? "",
                                CompletedStation = dtLastStatus.Rows[i]["CompletedStation"].ToString() ?? "",
                                PretestStation = dtLastStatus.Rows[i]["PretestStation"].ToString() ?? "",
                                IsEnd = dtLastStatus.Rows[i]["IsEnd"].ToString() == "Y" ? "是" : "否",
                                Actor = dtLastStatus.Rows[i]["Actor"].ToString(),
                                CreateAt = dtLastStatus.Rows[i]["CreateAt"].ToString()
                            });
                        }
                        dtTracking = lstDts[lstDts.Count-1];
                        Tracking = new ObservableCollection<TrackingEntity>();
                        for (int i = 0; i < dtTracking.Rows.Count; i++)
                        {
                            Tracking.Add(new TrackingEntity
                            {
                                Sn = dtTracking.Rows[i]["Sn"].ToString() ?? "",
                                WO = dtTracking.Rows[i]["WO"].ToString() ?? "",
                                Station = dtTracking.Rows[i]["Station"].ToString() ?? "",
                                Result = dtTracking.Rows[i]["Result"].ToString() ?? "",
                                FailDescription = dtTracking.Rows[i]["FailDescription"].ToString() ?? "",
                                FailValue = dtTracking.Rows[i]["FailValue"].ToString() ?? "",
                                EquipmentName = dtTracking.Rows[i]["EquipmentName"].ToString() ?? "",
                                TestSequence = dtTracking.Rows[i]["TestSequence"].ToString() ?? "",
                                Duration = dtTracking.Rows[i]["Duration"].ToString() ?? "",
                                Shift = dtTracking.Rows[i]["Shift"].ToString() ?? "",
                                Actor = dtTracking.Rows[i]["Actor"].ToString() ?? "",
                                CreateAt = dtTracking.Rows[i]["CreateAt"].ToString() ?? ""
                            });
                        }
                    }
                }
                else
                {
                    MessageBox.Show(arrayMsg[1],"软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
                }
            }
           
        }
        /// <summary>
        ///序列号回车事件处理
        /// </summary>
        private void PackingSNEnterHandler()
        {
            Check();//自动触发检查按钮
        }
        /// <summary>
        /// 填充机种信息到下拉列表框
        /// </summary>
        private void FillPNsToComboBox()
        {
            Task.Run(() => {
                DataTable dtPNs = new DataTable();
                dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
                Application.Current.Dispatcher.BeginInvoke(new Action(()=> {
                    PNs = new ObservableCollection<PartNumberEntity>();
                    for (int i = 0; i < dtPNs.Rows.Count; i++)
                    {
                        PNs.Add(new PartNumberEntity
                        {
                            PN = dtPNs.Rows[i]["PartNumber"].ToString()
                        });
                    }
                    SelectIndex = 0;
                }));
            });
           
        }
        //过滤机种信息
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }
        #endregion
    }
}
